import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import httpFetch from 'share/httpFetch';
import config from 'config'
import menuRoute from 'routes/menuRoute'
import SlideFrame from 'components/slide-frame'
import BasicInfo from 'components/basic-info'
import { Button, Select, Row, Col, Input, Popover, Icon, Badge, message } from 'antd'
import classNames from 'classnames';
import SubjectSheetDetailMaintain from 'containers/setting/subject-sheet/subject-sheet-detail-maintain'
import SubSubjectMaintain from 'containers/setting/subject-sheet/sub-subject-maintain'
const Search = Input.Search;
const Option = Select.Option;
import ResizeTable from "components/resize-table";
import ExportModal from 'components/template/export-modal/export-modal';
import Importer from 'components/template/importer';

/**
 * 科目表详情
 */
class SubjectSheetDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      updateState: false,
      pagination: {
        total: 0,
        page: 0,
        pageSize:10,
        current: 1,
        showSizeChanger:true,
        showQuickJumper:true,
      },
      value: '',
      focus: false,
      infoData: {},
      tableData: [],
      params: {},
      updateParams: {},
      subParams: {},//子科目的参数
      showSlideFrameNew: false,// 新增/编辑
      showSlideFrameSub: false,// 子科目
      showSlideFrameFromTo: false,
      showSlideFrameTitle: '',
      accountSetId: '',
      accountTypeOptions: [], //科目类型
      subjectDefine: menuRoute.getRouteItem('subject-sheet', 'key'),//返回到科目表定义
      searchParams: {
        info: '',
        accountType: ''
      },
      searchForm: [
        { type: 'input', id: 'accountSetCode', disabled: true, label: messages('setting.key1049'/*科目表代码*/) },
        { type: 'input', id: 'accountSetDesc', disabled: true, label: messages('setting.key1051'/*科目表名称*/) },
        {
          type: 'switch', id: 'enabled', label: messages('common.column.status'),
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
              text={enabled ? messages('common.enabled') : messages('common.disabled')} />)
        },
      ],
      columns: [
        {
          title: messages('setting.key1043'/*科目代码*/),
          key: 'accountCode',
          dataIndex: 'accountCode',
          width: '10%',
          "align": "center",
          render: (text) => {return <Popover content={text}>{text}</Popover>}
        },
        {
          title: messages('setting.key1044'/*科目名称*/),
          key: 'accountDesc',
          dataIndex: 'accountDesc',
          width: '10%',
          "align": "center",
          render: accountDesc => (<Popover content={accountDesc}>{accountDesc}</Popover>)
        },
        {
          title: messages('setting.key1054'/*余额方向*/),
          key: 'balanceDirectionName',
          dataIndex: 'balanceDirectionName',
          width: '10%',
          "align": "center",
        },
        {
          title: messages('setting.key1047'/*科目类型*/),
          key: 'accountTypeName',
          dataIndex: 'accountTypeName',
          width: '10%',
          "align": "center",
        },
        {
          title: messages('setting.key1055'/*报表类型*/),
          key: 'reportTypeName',
          dataIndex: 'reportTypeName',
          width: '10%',
          "align": "center",
        },
        {
          title: messages('setting.key1056'/*是否汇总*/),
          key: 'summaryFlag',
          dataIndex: 'summaryFlag',
          width: '10%',
          "align": "center",
          render: summaryFlag => (
            <Badge status={summaryFlag ? 'success' : 'error'}
              text={summaryFlag ? messages('common.yes') : messages('common.no')} />
          )
        },
        {
          title: messages('common.column.status'),
          key: 'enabled',
          dataIndex: 'enabled',
          width: '6%',
          "align": "center",
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
              text={enabled ? messages('common.status.enable') : messages('common.status.disable')} />
          )
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', width: '10%',  key: "operation", "align": "center",
          render: (text, record) => {
            if (record.summaryFlag) {
              return (<div>
                <span>
                  <a onClick={(e) => this.editItem(record)}>{messages('common.edit')/*编辑*/}</a>
                  <span className="ant-divider" />
                  <a style={{ marginRight: 10 }} onClick={(e) => this.subSubjectItem(record.id, this.props.params.accountSetId)}>{messages('setting.key1057'/*子科目*/)}</a>
                </span>
              </div>)
            } else {
              return (<div>
                <a onClick={(e) => this.editItem(record)}>{messages('common.edit')/*编辑*/}</a>
              </div>)
            }
          }
        }
      ],
      showOfferImportModal: false
    }
  }

  //初始化加载
  componentWillMount() {
    //根据科目表ID，取科目表信息
    httpFetch.get(`${config.baseUrl}/api/account/set/${this.props.params.accountSetId}`).then(res => {
      this.setState({ infoData: res.data });
    });
    //获取科目明细列表数据
    this.getList();
  };

  //获取 科目类型的值列表
  clickAccountTypeSelect = () => {
    //console.log("clickAccountTypeSelect:" + this.state.accountTypeOptions);
    //如果已经有值，则不再查询
    if (this.state.accountTypeOptions != '' && this.state.accountTypeOptions != undefined) {
      return;
    }
    this.getSystemValueList(2205).then(res => { //科目类型
      let accountTypeOptions = res.data.values || [];
      this.setState({ accountTypeOptions })
    });
  };

  //获取科目明细列表数据
  getList() {
    this.setState({ loading: true });
    let url = `${config.baseUrl}/api/accounts/query?accountSetId=${this.props.params.accountSetId}&info=${this.state.searchParams.info}&accountType=${this.state.searchParams.accountType}&size=${this.state.pagination.pageSize}&page=${this.state.pagination.page}`;
    return httpFetch.get(url).then((response) => {
      response.data.map((item,index) => {
        item.index = this.state.pagination.page * this.state.pagination.pageSize + index + 1;
        item.key = item.id;
      });
      this.setState({
        tableData: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
        },
      })
    }).catch((e) => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    });
  }

   //分页点击
   onChangePager = (pagination,filters, sorter) =>{
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      pagination: temp
    }, ()=>{
      this.getList();
    })
  };

  //点击搜索
  searchAccountDetailList = (values) => {
    let temp = this.state.pagination;
    temp.page = 0;
    temp.current = 1;
    temp.pageSize = 10;
    if (values === undefined) {
      values = '';
    }
    let searchParams = {
      ...this.state.searchParams,
      info: values
    };
    this.setState({
      searchParams: searchParams,
      loading: true,
      pagination: temp
    }, () => {
      this.getList();
    })
  };

  //表格上的子科目
  subSubjectItem = (recordId, accountSetId) => {
    this.setState({
      showSlideFrameSub: true,
      subParams: { record: { accountId: recordId, accountSetId: accountSetId } },
    })
  };

  //表格上的编辑
  editItem = (record) => {
    this.showSlideNew(true, record, this.state.accountTypeOptions, false)
  };
  //点击新建
  handleCreate = () => {
    let record = { accountSetId: this.props.params.accountSetId };
    this.showSlideNew(true, record, this.state.accountTypeOptions, true);
  }
  //设置侧拉
  showSlideNew = (flag, record, accountTypeOptions, isNew) => {
    this.setState({
      showSlideFrameNew: flag,
      updateParams: { record: record, accountTypeOptions, isNew },
      showSlideFrameTitle: isNew ? messages('setting.key1058'/*新建科目*/) : messages('setting.key1059'/*编辑科目*/)
    })
  };

  //侧拉关闭
  afterClose = (props) => {
    // 侧拉框的保存 this.props.close(true);//会调用
    if (props) {
      //刷新
      this.setState({ showSlideFrameNew: false, showSlideFrameSub: false }, () => {
        this.getList()
      });
    } else {
      //取消 不刷新
      this.setState({ showSlideFrameNew: false, showSlideFrameSub: false });
    }
  }
  //头编辑时点保存
  headerUpdateHandle = (values) => {
    //e.preventDefault();
    this.setState({ loading: true });
    let toValue = {
      ...this.props.params,
      ...values,//如果与this.props.params有冲突，则以values里的值为准
      id: this.props.params.accountSetId
    }
    httpFetch.put(`${config.baseUrl}/api/account/set`, toValue).then((res) => {
      this.setState({
        infoData: res.data,
        loading: false,
        updateState: true
      }, () => {
        message.success(messages('setting.key260'/*修改成功*/));
      });
    }).catch((e) => {
      this.setState({ loading: false });
      message.error(messages('common.save.filed') + `${e.response.data.message}`);
    })
  };

  // 查询条件 科目类型发生改变时，给state里赋值
  accountTypeChange = (values) => {
    //当为all时，表示查询时不受该字段限制
    if (values === "all") {
      values = "";
    }
    let searchParams = {
      accountType: values,
    };
    this.setState({
      searchParams: searchParams,
    });
  };

  openOfferImport = flag => {
    this.setState({showOfferImportModal: flag});
  };

  importOfferFile = () => {
    this.openOfferImport(false);
    this.getList();
  };

  render() {
    const { loading, infoData, searchForm, accountTypeOptions, showSlideFrameNew, showSlideFrameSub, showOfferImportModal,
      subjectDefine, subParams, tableData, updateState, pagination, columns, updateParams, searchParams } = this.state;
    const { tenantInfo, params } = this.props;
    const btnCls = classNames({
      'ant-search-btn': true,
      'ant-search-btn-noempty': !!this.state.value.trim(),
    });
    const searchCls = classNames({
      'ant-search-input': true,
      'ant-search-input-focus': this.state.focus,
    });
    return (
      <div className="budget-journal">
        <BasicInfo infoList={searchForm} ref="subject_ref" infoData={infoData} loading={loading}
          updateState={updateState}
          updateHandle={this.headerUpdateHandle} />
        <div className="table-header">
          <div className="table-header-title">
            <h2>{messages('setting.key1053'/*科目明细*/)}</h2>
          </div>
          <div className="table-header-buttons">
            <Row>
              <Col span="17">
                <Button type="primary"
                onClick={this.handleCreate}>{messages('common.create')}
                </Button>
                <Button onClick={() => this.openOfferImport(true)}>{messages('setting.key2203')/*导入科目*/}</Button>
                <ExportModal
                  style={{ display: 'inline-block' }}
                  type={'btn'}
                  exportTitle={messages('setting.key2204')/*导出科目详情*/}
                  exportType="ACCOUNTS_EXPORT"
                  exportCondition={{
                    accountsExportCommand: {
                      accountSetId: params.accountSetId,
                      accountType: searchParams.accountType,
                      accountCodeOrName: searchParams.info
                    }
                  }}
                  exportCommand={""}
                />
              </Col>
              <Col span="3">
                <Select defaultValue="all" style={{ width: 136 }} onChange={this.accountTypeChange} onFocus={this.clickAccountTypeSelect}>
                  <Option key='all'>{messages('common.all')}</Option>
                  {accountTypeOptions.map(option => {
                    return <Option key={option.value}>{option.messageKey}</Option>
                  })}
                </Select>
              </Col>
              <Col span="4">
                <Search
                  placeholder={messages('setting.key1060'/*科目代码/名称*/)}
                  onSearch={this.searchAccountDetailList}
                  enterButton={messages('common.search')}
                />
              </Col>
            </Row>
          </div>
          <ResizeTable
            rowKey={record => record.id}
            columns={columns}
            dataSource={tableData}
            pagination={pagination}
            loading={loading}
            onChange={this.onChangePager}
            bordered
            /*onRowClick={this.editItem}*/
            size="middle"
          />
          <div style={{fontSize: 14,margin: '20px 0',}}>
            <a onClick={() => {this.context.router.push(subjectDefine.url)}}><Icon type="rollback" />{messages("common.back")/*返回*/}</a>
          </div>
          {/* 科目明细 */}
          <SlideFrame title={this.state.showSlideFrameTitle}
            show={showSlideFrameNew}
            content={SubjectSheetDetailMaintain}
            afterClose={this.afterClose}// 取消和确定的时候执行
            onClose={() => { this.setState({ showSlideFrameNew: false }) }}// 点击 侧拉之外的地方时触发
            params={updateParams} />
          {/* 子科目 */}
          <SlideFrame title={messages('setting.key1057'/*子科目*/)}
            show={showSlideFrameSub}
            content={SubSubjectMaintain}
            afterClose={this.afterClose}// 取消和确定的时候执行
            onClose={() => { this.setState({ showSlideFrameSub: false, showSlideFrameFromTo: false }) }}// 点击 侧拉之外的地方时触发
            params={subParams} />
          <Importer
            visible={showOfferImportModal}
            isSpecial
            title={messages('setting.key2203')/*导入科目*/}
            templateUrl={`${config.baseUrl}/api/accounts/export/template`}
            uploadUrl={`${config.baseUrl}/api/accounts/import?accountSetId=${params.accountSetId}&tenantId=${tenantInfo.id}`}
            errorUrl={`${config.baseUrl}/api/accounts/export/errorMsg/of/account/import`}
            listenUrl={`${config.baseUrl}/api/batch/transaction/logs/customenumerationitem`}
            fileName={messages('setting.key1048')/*科目表*/}
            onOk={this.importOfferFile}
            accept={'.xlsx'}
            afterClose={() => this.openOfferImport(false)}
          />
        </div>
      </div>
    );
  }
}

SubjectSheetDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant
  }
}

export default connect(mapStateToProps)(SubjectSheetDetail);
